<template>
	<div class="game-container report-container">
		<div class="params">
			<el-form
				ref="form"
				:inline="true"
				:model="queryData"
				label-width="auto"
			>
				<el-form-item
					:label="$t('common.choose_merchant') + ':'"
					prop="merchantId"
				>
					<merchant-select
						v-model="queryData.merchantId"
						:placeholder="$t('common.please_choose')"
						:merchantInfo.sync="searchmerchantInfo"
					></merchant-select>
				</el-form-item>
				<el-form-item
					:label="
						$t('operation.deposit_config.pay_channel_name') + ':'
					"
				>
					<el-input
						v-model="queryData.payChannelName"
						clearable
						size="medium"
						:placeholder="$t('common.please_enter')"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="$t('operation.deposit_config.pay_type') + ':'"
				>
					<el-select
						v-model="queryData.payType"
						size="medium"
						:placeholder="$t('common.select_all')"
						clearable
					>
						<el-option
							v-for="item in payTypeList"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('common.last_updateAt') + ':'">
					<el-date-picker
						v-model="searchTime"
						size="medium"
						:picker-options="pickerOptions"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_date')"
						:end-placeholder="$t('common.end_date')"
						align="right"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="content">
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				:header-cell-style="getRowClass"
			>
				<el-table-column
					type="index"
					align="center"
					:label="$t('common.serial_number')"
					width="80"
				>
					<template slot-scope="scope">
						<span>{{ getSerialNum(scope.$index) }}</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="channelName"
					align="center"
					:label="$t('operation.deposit_config.pay_channel_name')"
				>
					<template slot-scope="scope">
						{{ scope.row.channelName || '-' }}
					</template>
				</el-table-column>
				<!-- <el-table-column
					prop="paymentChannelName"
					align="center"
					:label="$t('operation.deposit_config.payment_channel_name')"
				></el-table-column> -->
				<el-table-column
					prop="payName"
					align="center"
					:label="$t('operation.deposit_config.pay_type')"
				>
					<template slot-scope="scope">
						{{ scope.row.payName || '-' }}
					</template>
				</el-table-column>

				<el-table-column
					prop="discountScale"
					align="center"
					:label="$t('operation.deposit_config.preferential_ratio')"
				></el-table-column>
				<el-table-column
					prop="maxQuota"
					align="center"
					:label="
						$t('operation.deposit_config.day_max_preferential') +
							`（${currentCurrency}）`
					"
				>
					<template slot-scope="scope">
						<span>
							{{
								scope.row.maxQuota
									| filterDecimalsN(
										currentCurrency === '₫' ? 0 : 2
									)
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					prop="status"
					align="center"
					:label="$t('operation.deposit_config.preferential_status')"
				>
					<template slot-scope="scope">
						<el-switch
							v-if="hasPermission('504011')"
							v-model="scope.row.status"
							:active-value="1"
							:inactive-value="0"
							@change="handleSwitch($event, scope.row)"
						></el-switch>
					</template>
				</el-table-column>
				<el-table-column
					prop="updatedAt"
					align="center"
					:label="$t('common.last_updateAt')"
				></el-table-column>
				<el-table-column
					prop="operator"
					align="center"
					:label="$t('common.last_updateBy')"
				></el-table-column>
				<el-table-column align="center" :label="$t('common.actions')">
					<!-- v-if="hasPermission('872')" -->
					<template slot-scope="scope">
						<el-button
							v-if="hasPermission('504012')"
							type="primary"
							icon="el-icon-edit"
							size="medium"
							:disabled="scope.row.status === 1"
							@click="edit(scope.row)"
						>
							{{ $t('common.edit') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				:current-page.sync="pageNum"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</div>
		<el-dialog
			:title="$t('operation.deposit_config.deposit_preferential_config')"
			:visible.sync="dialogFormVisible"
			:destroy-on-close="true"
			class="rempadding"
			width="780px"
			@close="clear"
		>
			<el-divider></el-divider>
			<el-form ref="formSub" :model="dialogForm" label-width="auto">
				<h3>{{ $t('operation.deposit_config.info') }}</h3>
				<el-form-item
					:label="$t('operation.deposit_config.pay_type') + ':'"
					prop="payType"
				>
					<el-input
						disabled
						size="medium"
						:value="rowData.payName || '-'"
						style="width:260px"
					></el-input>
				</el-form-item>
				<el-form-item
					:label="
						$t('operation.deposit_config.pay_channel_name') + ':'
					"
					prop="payChannelName"
				>
					<el-input
						:value="rowData.channelName || '-'"
						clearable
						disabled
						size="medium"
						:placeholder="$t('common.please_enter')"
						style="width:260px"
					></el-input>
				</el-form-item>

				<h3>{{ $t('operation.deposit_config.preferential_set') }}</h3>
				<el-table
					:data="dialogForm.arr"
					border
					:header-cell-style="getRowClass"
					class="dialog-table"
				>
					<el-table-column
						:label="
							$t('operation.deposit_config.preferential_ratio')
						"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="'arr.' + scope.$index + '.discountScale'"
								:rules="[
									{ validator: validateDiscountScale },
									{
										required: true,
										message: $t('common.please_enter'),
										trigger: 'blur'
									}
								]"
							>
								<!-- :min="0.01" -->
								<el-input-number
									v-model="scope.row.discountScale"
									:placeholder="$t('common.please_enter')"
									:max="100"
									clearable
									:controls="false"
									@blur="(e) => vauleSet(e, 'discountScale')"
								></el-input-number>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column
						:label="
							$t(
								'operation.deposit_config.day_max_preferential'
							) + `(${currentCurrency})`
						"
					>
						<template slot-scope="scope">
							<el-form-item
								:prop="'arr.' + scope.$index + '.maxQuota'"
								:rules="[
									{ validator: validateMaxQuota },
									{
										required: true,
										message: $t('common.please_enter'),
										trigger: 'blur'
									}
								]"
							>
								<!-- :min="currentCurrency === '₫' ? 100 : 0.01" -->
								<el-input-number
									v-model="scope.row.maxQuota"
									:placeholder="$t('common.please_enter')"
									:max="maxQuota"
									clearable
									:controls="false"
									@blur="vauleSet('maxQuota')"
								></el-input-number>
							</el-form-item>
						</template>
					</el-table-column>
				</el-table>
				<div class="text-color">
					{{ $t('operation.deposit_config.tips1') }}
				</div>
				<div class="text-color">
					{{ $t('operation.deposit_config.tips2')
					}}{{ tips.preferentialRatioTips }}
				</div>
				<div class="text-color">
					{{ $t('operation.deposit_config.tips3')
					}}{{ tips.maxQuotaTips }}
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button
					type="primary"
					:loading="loading"
					@click="subAddOrEidt"
				>
					{{ $t('common.confirm') }}
				</el-button>
				<el-button @click="dialogReset">
					{{ $t('common.reset') }}
				</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { Decimal } from 'decimal.js'
import { routerNames } from '@/utils/consts'
export default {
	name: routerNames.memberDiscountConfig,
	mixins: [list],
	data() {
		return {
			carouselData: [],
			pageNum: 1,
			pageSize: 100,
			activeName: '1',
			queryData: {
				payType: undefined,
				merchantId: undefined
			},
			queryStatus: false,
			searchTime: [],
			tableData: [],
			dialogFormVisible: false,
			rowVal: {},
			dialogForm: {
				arr: [
					{
						discountScale: '',
						maxQuota: ''
					}
				]
			},
			currentCurrency: '',
			// enabledList: [],
			rowData: {},
			searchmerchantInfo: {},
			total: 0
		}
	},
	computed: {
		// enumTywalletPayType() {
		// 	return this.globalDics.depositPaymentChannelType || []
		// },
		payTypeList() {
			return this.globalDics.depositPaymentType || []
		},
		// 每日最高优惠
		maxQuota() {
			if (this.currentCurrency === '₫') {
				return 1000000000
			}
			return 1000000
		},
		tips() {
			const obj = {
				maxQuotaTips: '0.01~1000000.00',
				preferentialRatioTips: '0.01~100.00'
			}
			if (this.currentCurrency === '₫') {
				obj.maxQuotaTips = '100～1000000000.00'
				obj.preferentialRatioTips = '0.01~100.00'
			}
			if (this.currentCurrency === '฿') {
				obj.maxQuotaTips = '0.01~1000000.00'
				obj.preferentialRatioTips = '0.01~100.00'
			}
			return obj
		}
	},
	mounted() {
		if (!this.$store.getters.isZk) {
			this.queryData.merchantId = this.$store.getters.merchantInfo.id
			this.search()
		}

		// this.queryPaymentMerchantConfigEnabled()
	},
	methods: {
		validateDiscountScale(rule, value, callback) {
			if (value === '') {
				return callback(new Error(this.$t('common.please_enter')))
			}
			if (Number(value < 0.01)) {
				return callback(
					new Error(
						`${this.$t(
							'operation.deposit_config.input_scope'
						)}0.01~100.00`
					)
				)
			}
			callback()
		},
		validateMaxQuota(rule, value, callback) {
			if (value === '') {
				return callback(new Error(this.$t('common.please_enter')))
			}
			if (
				Number(value) < (this.currentCurrency === '₫' ? '100.00' : 0.01)
			) {
				return callback(
					new Error(
						`${this.$t('operation.deposit_config.input_scope')}${
							this.currentCurrency === '₫' ? '100.00' : 0.01
						} ~${this.maxQuota}.00`
					)
				)
			}
			callback()
		},
		loadData() {
			if (!this.queryData.merchantId) {
				this.loading = true
				this.tableData = []
				this.total = 0
				setTimeout(() => (this.loading = false), 500)
				return
			}
			this.tableData = []
			this.loading = true
			this.queryStatus = true
			const [startTime, endTime] = this.searchTime || []
			const params = {
				...this.queryData,
				pageSize: this.pageSize,
				pageNum: this.pageNum,
				startTime: startTime
					? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined,
				endTime: endTime
					? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
					: undefined
			}
			// params = {
			// 	...this.getParams(params)
			// }
			this.$api
				.getOperateActivityConfigQuery(params)
				.then((res) => {
					this.tableData = res.data.record || []
					this.currentCurrency = this.searchmerchantInfo.currencySymbol
					this.tableData.forEach((item) => {
						item.discountScale = new Decimal(item.discountScale)
							.mul(new Decimal(100))
							.toNumber()
					})
					this.total = res.data.totalRecord
					this.loading = false
				})
				.catch(() => {
					this.loading = false
				})
		},
		search() {
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.queryData.payType = undefined
			this.queryData.payChannelName = undefined
			this.tableData = []
			this.searchTime = []
			this.queryStatus = false
			if (!this.$store.getters.isZk) {
				this.queryData.merchantId = this.$store.getters.merchantInfo.id
				this.search()
			} else {
				this.queryData.merchantId = undefined
			}
		},
		handleSwitch(val, row) {
			const params = {
				id: row.id,
				status: val,
				payType: row.payType
			}
			this.$api.getOperateActivityConfigUpdateStatus(params).then(() => {
				this.$message.success(this.$t('common.modify_success'))
				this.loadData()
			})
		},
		edit(val) {
			this.rowData = val
			this.dialogForm = {
				arr: [
					{
						discountScale: '',
						maxQuota: ''
					}
				]
			}
			this.rowVal = { ...val }
			this.dialogForm.id = val.id
			this.dialogForm.arr[0].discountScale = val.discountScale
			this.dialogForm.arr[0].maxQuota = val.maxQuota
			this.dialogFormVisible = true
			this.$nextTick(() => {
				this.$refs.formSub.clearValidate()
			})
		},
		vauleSet(val) {
			if (this.dialogForm.arr[0][val]) {
				if (this.currentCurrency === '₫') {
					this.dialogForm.arr[0][val] = new Decimal(
						this.dialogForm.arr[0][val]
					).toFixed(0)
				} else {
					this.dialogForm.arr[0][val] = new Decimal(
						this.dialogForm.arr[0][val]
					).toFixed(2, Decimal.ROUND_DOWN)
				}
			}
		},

		subAddOrEidt() {
			const maxQuota = this.dialogForm.arr[0].maxQuota
			const discountScale = this.dialogForm.arr[0].discountScale
			const num = new Decimal(discountScale)
				.div(new Decimal(100))
				.toNumber()
			const data = {
				id: this.rowVal.id,
				payType: this.rowVal.payType,
				maxQuota: maxQuota,
				discountScale: num
			}
			this.$refs.formSub.validate((valid) => {
				if (valid) {
					this.loading = true
					this.$api
						.getOperateActivityConfigEdit(data)
						.then((res) => {
							this.loading = false
							if (res?.code === 200) {
								this.$message.success(
									this.$t('common.edit_success')
								)
								this.pageNum = 1
								this.loadData()
							}
							this.dialogFormVisible = false
						})
						.catch((e) => {
							this.loading = false
						})
				}
			})
		},
		dialogReset() {
			this.$refs.formSub.resetFields()
		},
		clear() {
			this.$refs.formSub.clearValidate()
		},
		// queryPaymentMerchantConfigEnabled() {
		// 	this.$api.queryPaymentMerchantConfigEnabled(1).then((res) => {
		// 		this.enabledList = res?.data || []
		// 	})
		// },
		handleSizeChange(value) {
			this.pageNum = 1
			this.pageSize = value
			this.loadData()
		},
		handleCurrentChange(value) {
			this.pageNum = value
			this.loadData()
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
	padding: 20px 20px 0px;
}
::v-deep .rempadding .el-dialog__body {
	padding: 0;
	padding-bottom: 30px;
	form {
		padding: 0 40px;
	}
}
.payTypestyle {
	z-index: 999999999999 !important;
}
.dialog-table {
	margin-bottom: 30px;
	::v-deep th .cell {
		text-align: center;
	}
	::v-deep .el-form-item {
		margin: 22px 0;
	}
}
.text-color {
	color: #d9001b;
}
.dialog-footer {
	text-align: center;
}
</style>
